package controllers;

import helpers.GeneralHelper;
import helpers.StringHelper;
import helpers.UrlHelper;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import javax.cache.Cache;
import javax.script.Bindings;
import javax.script.CompiledScript;
import javax.script.ScriptContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import admin.models.MetaSeoModel;

import models.CategoryModel;

import quercus.CompileScriptEngine;
import systems.ConfigSystem;
import systems.Recently;
import systems.RecentlyTag;

import entities.Ads;
import entities.ApplicationTemplate;
import entities.Article;
import entities.Category;
import entities.MetaSeo;
import entities.SeoData;
import entities.SiteConfig;

public class GoogleSearchServlet extends HttpServlet{
	public void doGet(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException {
		
		SiteConfig config = ConfigSystem.getConfigs();
		ApplicationTemplate appTemplate = ConfigSystem.getTemplate();
		
		if (appTemplate == null) {
			response.getWriter().println("Please enter template");
			return ;
		}
		
		Cache memCache = GeneralHelper.getCache();
		
		String name = request.getParameter("q");
		
		//Get list category
		CategoryModel categoryModel = CategoryModel.getInstance();
		List<Category> lstCategories = categoryModel.getAll();
		
		//Get tags
		List<String> tags = RecentlyTag.getTags();
		
		//Get recently article view
		List<Article> lastestArticles = Recently.getArticles("", "lastest_article");
		
		//Set adsense content
		Ads ads = new Ads();
		
		/******************************Set page template ******************************/
		String layout_for_content = "";
		String layout_for_header = "";
		String layout_for_footer = "";
		
		String cacheLayoutName = config.getCachePrefix() + "_layout";
		String cacheHeaderName = config.getCachePrefix() + "_header";
		String cacheFooterName = config.getCachePrefix() + "_footer";
		String cacheContentName = config.getCachePrefix() + "_key_" + name + "_content";
		
		
		layout_for_content = (String) memCache.get(cacheContentName);
		if (layout_for_content == null) {
			//String contentPage = StringHelper.getContentPhp("/templates/classic/gsearch.php", getServletContext());
			String contentPage = appTemplate.getSearch();
			String library = appTemplate.getLibrary();
			CompiledScript compiledContent = CompileScriptEngine.getCompileScript(config.getCachePrefix(), "layout_for_content", contentPage);
			
			//Set value
			if (compiledContent != null) {
				Bindings bind = compiledContent.getEngine().getBindings(ScriptContext.ENGINE_SCOPE);
				bind.put("name", name);
				bind.put("cxGoogleSearch", config.getCxGoogleSearch());
				bind.put("lstCategories", lstCategories);
				bind.put("tags", tags);
				bind.put("lastestArticles", lastestArticles);
				bind.put("baseUrl", appTemplate.getBaseUrl());
				bind.put("library", library);
				bind.put("ads", ads);
				bind.put("siteConfig", config);
			}
			
			try {
				layout_for_content = (String) compiledContent.eval();
			} catch (Exception e) {
				// TODO: handle exception
			}
			
			memCache.put(cacheContentName, layout_for_content);
		} 
		
		layout_for_header = (String) memCache.get(cacheHeaderName);
		if (layout_for_header == null) {
			//String headerPage = StringHelper.getContentPhp("/templates/classic/header.php", getServletContext());
			String headerPage = appTemplate.getHeader();
			CompiledScript compiledHeader = CompileScriptEngine.getCompileScript(config.getCachePrefix(), "layout_for_header", headerPage);
			try {
				layout_for_header = (String) compiledHeader.eval();
			} catch (Exception e) {
				// TODO: handle exception
			}
			
			memCache.put(cacheHeaderName, layout_for_header);
		}
		
		
		layout_for_footer = (String) memCache.get(cacheFooterName);
		if (layout_for_footer == null) {
			//String footerPage = StringHelper.getContentPhp("/templates/classic/footer.php", getServletContext());
			String footerPage = appTemplate.getFooter();
			CompiledScript compiledFooter = CompileScriptEngine.getCompileScript(config.getCachePrefix(), "layout_for_footer", footerPage);
			try {
				layout_for_footer = (String) compiledFooter.eval();
			} catch (Exception e) {
				// TODO: handle exception
			}
			
			memCache.put(cacheFooterName, layout_for_footer);
		}
		
		String layoutPage = (String) memCache.get(cacheLayoutName);
		if (layoutPage == null) {
			//layoutPage = StringHelper.getContentPhp("/templates/classic/layouts.php", getServletContext());
			layoutPage = appTemplate.getLayout();
			memCache.put(cacheLayoutName, layoutPage);
		}
		
		layoutPage = layoutPage.replace("$layout_for_header", layout_for_header);
		layoutPage = layoutPage.replace("$layout_for_content", layout_for_content);
		layoutPage = layoutPage.replace("$layout_for_footer", layout_for_footer);
		
		//Set content for Seo
		Map<String, String> replates = new TreeMap<String, String>();
		replates.put("__SERVER_NAME__", UrlHelper.getDomainServer(request));
		replates.put("__SERVER_URL__", UrlHelper.getServerUrl(request));
		
		MetaSeoModel metaseoModel = MetaSeoModel.getInstance();
		MetaSeo metaseo = metaseoModel.get("gsearch");
		
		String sitename = config.getSiteName();
		String metaTitle = StringHelper.replateContent(metaseo.getTitle(), replates);
		String metaDescription = StringHelper.replateContent(metaseo.getDescription(), replates);
		String metaKeywords = StringHelper.replateContent(metaseo.getKeywords(), replates);
		String ogurl = StringHelper.replateContent(metaseo.getOgurl(), replates);
			
		layoutPage = layoutPage.replace("__META_TITLE__", metaTitle);
		layoutPage = layoutPage.replace("__META_DESCRIPTION__", metaDescription);
		layoutPage = layoutPage.replace("__META_KEYWORD__", metaKeywords);
		layoutPage = layoutPage.replace("__OG_SITE_NAME__", sitename);
		layoutPage = layoutPage.replace("__OG_TITLE__", metaTitle);
		layoutPage = layoutPage.replace("__OG_DESCRIPTION__", metaDescription);
		layoutPage = layoutPage.replace("__OG_URL__", ogurl);
		
		//Cache header
		response.addHeader("Cache-Control", "public, max-age=60000");
		
		try {
			response.getWriter().print(layoutPage);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
